package walkera.cn.httpserve.subscribers;


import android.content.Context;


import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import walkera.cn.httpserve.bean.MyException;
import walkera.cn.httpserve.bean.PicBean;


public class HttpSubscriber<T> implements Observer<T> {

    private PicInfoSubscriberListener subscriberOnListener;
	private Context context;
    private Disposable disposable;

    public HttpSubscriber( PicInfoSubscriberListener subscriberOnListener, Context context)
    {
        this.subscriberOnListener = subscriberOnListener;
		this.context = context;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
    }

    @Override
    public void onComplete() {
        if( (subscriberOnListener == null) ||  (context == null))
        {
            if(disposable != null && !disposable.isDisposed()){
                //切断订阅关系
                disposable.dispose();
            }
        }
    }

    @Override
    public void onError(Throwable e) {
        if(subscriberOnListener != null && context != null)
        {
            if (e instanceof SocketTimeoutException) {
                subscriberOnListener.onError(-1001, "网络超时，请检查您的网络状态");
            } else if (e instanceof ConnectException) {
                subscriberOnListener.onError(-1002, "网络链接中断，请检查您的网络状态");
            } else if(e instanceof MyException){
                subscriberOnListener.onError(((MyException)e).getCode(), ((MyException)e).getMsg());
            } else  {
                subscriberOnListener.onError(-1003, "未知错误:" + e.getMessage());
            }
        }  else  {
            if(disposable != null && !disposable.isDisposed()){
                disposable.dispose();
            }

        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onNext(T t) {
        if(subscriberOnListener != null && context != null)
        {
            // 收到想要的订阅信息 ，然后通过回到接口 发送到需要数据的地方
            subscriberOnListener.onSucceed((List<PicBean>) t);
        }  else  {
            if(disposable != null && !disposable.isDisposed()){
                disposable.dispose();
            }
        }
    }
}
